#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :model.py
# @Time      :2021/6/21 15:10
# @Author    : 刘广鸿

from sqlalchemy import String, Text, Integer, ForeignKey, Column, Float, DateTime
from sqlalchemy.orm import relationship
from dbs.database import Base


class Users(Base):
    __tablename__ = "users"
    """用户表"""
    id = Column(Integer, index=True, primary_key=True)
    username = Column(String, primary_key=True)
    password = Column(String, nullable=False)
    token = Column(String, server_default="NO token", nullable=False)  # 访问凭证
    devices = Column(Text, nullable=True)  # 所管理设备列表


class Devices(Base):
    __tablename__ = "devices"
    """"设备集"""
    id = Column(Integer, index=True, primary_key=True)
    uuid = Column(String, primary_key=True)
    type = Column(Integer, nullable=False)  # 0 -> 传感器  1 -> 执行器
    name = Column(String, nullable=False)  # 设备名称
    note = Column(String, nullable=True)  # 设备备注信息
    device_key = Column(String, nullable=False)  # 设备秘钥  uuid + 时间磋 =》MD5 加密
    Datas_set = relationship("Datas", back_populates="device")
    HistoryDatas = relationship("History", back_populates="device")


class Datas(Base):
    """数据集"""
    __tablename__ = "datas"
    id = Column(Integer, index=True, primary_key=True)
    type = Column(Integer, nullable=False)  # 数据类型 0传感器数据 1执行器数据 2网关设备数据 3其他数据类型
    value = Column(String, nullable=False)  # 数据值
    identifier = Column(String, nullable=False)  # 标识符
    datetime = Column(String, nullable=False)  # 时间
    deviceid = Column(String, ForeignKey("devices.uuid"), nullable=False)
    device = relationship("Devices", back_populates="Datas_set")  # 外键关联 Devices --> uuid


class History(Base):
    """历史数据表"""
    __tablename__ = "history"
    id = Column(String, primary_key=True)
    one_hour = Column(Text, nullable=True)
    eight_hours = Column(Text, nullable=True)
    twelve_hours = Column(Text, nullable=True)
    twenty_four_hours = Column(Text, nullable=True)
    device = relationship("Devices", back_populates="HistoryDatas")
